package com.bms.service;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.bms.comm.MyUserDetails;
import com.bms.dao.UserDao;

/** 
 * 一个自定义的service用来和数据库进行操作. 即以后我们要通过数据库保存权限.则需要我们继承UserDetailsService 
 * @author cyj 
 *  
 */ 
public class CustomUserDetailsService implements UserDetailsService {
	
	@Resource
	private UserDao userDao;
	
	@Override
	public MyUserDetails loadUserByUsername(String userName)
			throws UsernameNotFoundException {
		// TODO Auto-generated method stub
		
		MyUserDetails userDetails = null;  
		
		com.bms.bean.User user = (com.bms.bean.User) userDao.getUserByNickName(userName);
		
		if(user!=null){
			userDetails = new MyUserDetails(user.getNickName(),user.getPassWord(),getAuthority(user.getRoleId()),user);
		}else{
			userDetails = new MyUserDetails("游客","123456",getAuthority(0L),null);
		}
		return userDetails;
	}
	
	@SuppressWarnings("deprecation")
	private List<GrantedAuthority> getAuthority(Long roleId){
		
		List<GrantedAuthority> gaList = new ArrayList<GrantedAuthority>();
		if(roleId==1){
			gaList.add(new GrantedAuthorityImpl("ROLE_ADMIN"));
		}else if(roleId==2){
			gaList.add(new GrantedAuthorityImpl("ROLE_ROLE"));
		}else if(roleId==3){
			gaList.add(new GrantedAuthorityImpl("ROLE_USER"));
		}else{
			gaList.add(new GrantedAuthorityImpl("ROLE_ANYONE"));
		}
		return gaList;
	}
}
